<?php
/**
* @package Frontend-User-Access (com_frontenduseraccess)
* @version 3.0.8
* @copyright Copyright (C) 2008 Carsten Engel. All rights reserved.
* @license GPL versions free/trial/pro
* @author http://www.pages-and-items.com
* @joomla Joomla is Free Software
*/

// no direct access
defined('_JEXEC') or die('Restricted access');

jimport('joomla.application.component.controller');

class frontenduseraccessController extends JController{

	var $fua_config;	
	var $view;	
	var $has_usergroups = false;
	var $usergroups;
	var $db;
	var $user_type;
	var $bot_installed_system = false;
	var $bot_published_system = false;	
	var $bot_installed_content = false;
	var $bot_published_content = false;
	var $fua_demo_seconds_left;	
	var $version = '3.0.8';
	var $fua_version_type = 'pro';	//free trial or pro	

	function display(){		
		
		// Set a default view if none exists
		if (!JRequest::getVar('view')){			
			JRequest::setVar('view', $this->fua_config['default_tab'] );
		}
		
		//set header
		if(JRequest::getCmd('view')=='config' || JRequest::getCmd('view')=='expired' || JRequest::getCmd('view')=='importmoduleaccess'){
			$icon = 'cpanel.png';
		}else{
			$icon = 'user.png';
		}
		JToolBarHelper::title('Frontend User Access',$icon);
		
		parent::display();
				
	}
	
	
	function __construct(){	
		
		$this->fua_config = $this->get_config();				
		$this->view = JRequest::getVar('view');				
		
		if(!$this->fua_check_trial_version() && $this->view!='expired'){			
			$this->setRedirect("index2.php?option=com_frontenduseraccess&view=expired");			
		}	
		
		//get database		
		$this->db = JFactory::getDBO();		
		
		//check if bot is installed		
		if(file_exists(dirname(__FILE__).'/../../../plugins/system/frontenduseraccess.php')){
			$this->bot_installed_system = true;	
			//check if bot is published			
			$this->db->setQuery("SELECT published FROM #__plugins WHERE element='frontenduseraccess' AND folder='system' LIMIT 1");
			$rows = $this->db->loadObjectList();
			$row = $rows[0];						
			if($row->published==1){
				$this->bot_published_system = true;
			}		
		}		
		
		if(file_exists(dirname(__FILE__).'/../../../plugins/content/frontenduseraccess.php')){
			$this->bot_installed_content = true;	
			//check if bot is published			
			$this->db->setQuery("SELECT published FROM #__plugins WHERE element='frontenduseraccess' AND folder='content' LIMIT 1");
			$rows = $this->db->loadObjectList();
			$row = $rows[0];						
			if($row->published==1){
				$this->bot_published_content = true;
			}		
		}
		
		//check for usergroups
		$usergroups = false;
		$this->db->setQuery("SELECT id FROM #__fua_usergroups LIMIT 1");
		$rows = $this->db->loadObjectList();		
		if($rows[0]!=''){
			$this->has_usergroups = true;
		}
		
		//set var user_type		
		$user =& JFactory::getUser();		
		$this->user_type = $user->get('usertype');		
		
		parent::__construct();		
	}	
	
	function get_config(){	
			
		$database = JFactory::getDBO();			
		
		$database->setQuery("SELECT config "
		."FROM #__fua_config "
		."WHERE id='fua' "
		."LIMIT 1"
		);		
		$raw = $database->loadResult();		
		
		$params = explode( "\n", $raw);
		
		for($n = 0; $n < count($params); $n++){		
			$temp = explode('=',$params[$n]);
			$var = $temp[0];
			$value = '';
			if(count($temp)==2){
				$value = trim($temp[1]);
				if($value=='false'){
					$value = false;
				}
				if($value=='true'){
					$value = true;
				}
			}							
			$config[$var] = $value;	
		}	
		
		//reformat redirect urls		
		$config['redirect_url'] = str_replace('[equal]','=',$config['redirect_url']);
		$config['no_item_access_full_url'] = str_replace('[equal]','=',$config['no_item_access_full_url']);
		$config['no_category_access_url'] = str_replace('[equal]','=',$config['no_category_access_url']);
		$config['no_section_access_url'] = str_replace('[equal]','=',$config['no_section_access_url']);
		$config['no_component_access_url'] = str_replace('[equal]','=',$config['no_component_access_url']);
		$config['no_menu_access_url'] = str_replace('[equal]','=',$config['no_menu_access_url']);
				
		return $config;			
	}
	
	function get_var($name, $default = null, $hash = 'default', $type = 'none', $mask = 0){	
		$var = JRequest::getVar($name, $default, $hash, $type, $mask);		
		return $var;
	}		
	
	function echo_header(){	
	
		$this->check_demo_time_left();
				   
		if($this->user_type=='Super Administrator'){
			echo '<div id="config_link"><a href="index2.php?option=com_frontenduseraccess&amp;view=config">'.JText::_('CONFIG').'</a></div>'."\n";
		}		
		
		echo '<script src="../includes/js/overlib_mini.js" language="JavaScript" type="text/javascript"></script>'."\n";
		echo '<script src="components/com_frontenduseraccess/javascript/javascript.js" language="JavaScript" type="text/javascript"></script>'."\n";
		
		echo '<link href="components/com_frontenduseraccess/css/frontenduseraccess.css" rel="stylesheet" type="text/css" />'."\n";
			
		echo '<ul id="fua_menu">';
		if($this->fua_config['display_usergroups']){	
			echo '<li><a href="index2.php?option=com_frontenduseraccess&amp;view=usergroups"';
			if($this->view=='usergroups' || $this->view=='usergroup'){
				echo 'class="on"';
			}
			echo '><span>'.JText::_('USERGROUPS').'</span></a></li>';	
		}
		if($this->fua_config['display_users']){	
			echo '<li><a href="index2.php?option=com_frontenduseraccess&amp;view=users"';
			if($this->view=='users' || $this->view=='user'){
				echo 'class="on"';
			}
			echo '><span>'.JText::_('USERS').'</span></a></li>';
		}
		if($this->fua_config['display_items']){				
			echo '<li><a href="index2.php?option=com_frontenduseraccess&amp;view=items"';
			if($this->view=='items'){
				echo 'class="on"';
			}
			echo '><span>'.JText::_('ITEM_ACCESS').'</span></a></li>';
		}
		if($this->fua_config['display_categories']){
			echo '<li><a href="index2.php?option=com_frontenduseraccess&amp;view=categories"';
			if($this->view=='categories'){
				echo 'class="on"';
			}
			echo '><span>'.JText::_('CATEGORY_ACCESS').'</span></a></li>';
		}
		if($this->fua_config['display_sections']){
			echo '<li><a href="index2.php?option=com_frontenduseraccess&amp;view=sections"';
			if($this->view=='sections'){
				echo 'class="on"';
			}
			echo '><span>'.JText::_('SECTION_ACCESS').'</span></a></li>';	
		}
		if($this->fua_config['display_modules']){
			echo '<li><a href="index2.php?option=com_frontenduseraccess&amp;view=modules"';
			if($this->view=='modules'){
				echo 'class="on"';
			}
			echo '><span>'.JText::_('MODULE_ACCESS').'</span></a></li>';	
		}
		if($this->fua_config['display_components']){		
			echo '<li><a href="index2.php?option=com_frontenduseraccess&amp;view=components"';
			if($this->view=='components'){
				echo 'class="on"';
			}
			echo '><span>'.JText::_('COMPONENT_ACCESS').'</span></a></li>';
		}	
		if($this->fua_config['display_menuaccess']){		
			echo '<li><a href="index2.php?option=com_frontenduseraccess&amp;view=menuaccess"';
			if($this->view=='menuaccess'){
				echo 'class="on"';
			}
			echo '><span>'.JText::_('MENU_ACCESS').'</span></a></li>';
		}			
		echo '</ul>'."\n";		
		
		//message if there are no usergroups
		if(!$this->has_usergroups && $this->view!='usergroups' && $this->view!='usergroup'){
			echo '<div style="color: red; text-align: left;">'.JText::_('NOUSERGROUPS').'<br/><br/></div>';
		}				
		
		//message if bot is not installed	
		if(!$this->bot_installed_system){				
			echo '<div style="color: red; text-align: left;">'.JText::_('BOTNOTINSTALLED').' (system)<br/><br/></div>';
		}
		
		//message if bot is not published	
		if(!$this->bot_published_system){				
			echo '<div style="color: red; text-align: left;">'.JText::_('BOTNOTPUBLISHED').' (system)<br/><br/></div>';
		}	
		
		//message if bot is not installed	
		if(!$this->bot_installed_content){				
			echo '<div style="color: red; text-align: left;">'.JText::_('BOTNOTINSTALLED').' (content)<br/><br/></div>';
		}
		
		//message if bot is not published	
		if(!$this->bot_published_content){				
			echo '<div style="color: red; text-align: left;">'.JText::_('BOTNOTPUBLISHED').' (content)<br/><br/></div>';
		}			
	}		
	
	function usergroup_save(){			
			
		// Check for request forgeries 
		JRequest::checkToken() or jexit('Invalid Token');
		
		//get vars
		$id = intval($this->get_var('id', 0, 'post'));
		$name = strip_tags($this->get_var('name', '', 'post'));
		$description = strip_tags($this->get_var('description', '', 'post'));
		$url = $this->get_var('url', '', 'post');		
		$name = addslashes($name);
		$description = addslashes($description);		
		
		if($id==0){
			//new usergroup
			$this->db->setQuery( "INSERT INTO #__fua_usergroups SET name='$name', description='$description', url='$url' ");
			$this->db->query();
		}else{
			//edit usergroup
			$this->db->setQuery( "UPDATE #__fua_usergroups SET name='$name', description='$description', url='$url' WHERE id='$id' ");
			$this->db->query();
		}	
		
		//parse filter
		$filter = '';
		$search = JRequest::getVar('search', '');
		if($search){
			$filter .= '&search='.$search;
		}
		
		$this->setRedirect("index2.php?option=com_frontenduseraccess&view=usergroups".$filter, JText::_('USERGROUP_SAVED'));
	}	
	
	function usergroup_delete(){	
		
		// Check for request forgeries 
		JRequest::checkToken() or jexit('Invalid Token');			
		
		$cid = JRequest::getVar('cid', null, 'post', 'array');		
		
		if (!is_array($cid) || count($cid) < 1) {
			echo "<script> alert(".JText::_('SELECT_ITEM_TO_DELETE')."); window.history.go(-1);</script>";
			exit();
		}
		
		if (count($cid)){
			$ids = implode(',', $cid);			
			
			//update rows from user-index table which usergroup stops existing
			$this->db->setQuery("SELECT id FROM #__fua_userindex WHERE group_id IN ($ids)"  );
			$rows = $this->db ->loadObjectList();
			foreach($rows as $row){					
				$index_id = $row->id;
				$this->db->setQuery( "UPDATE #__fua_userindex SET group_id='0' WHERE id='$index_id'");
				$this->db->query();
			}		
			
			//delete usergroup
			$this->db->setQuery("DELETE FROM #__fua_usergroups WHERE id IN ($ids)");
			$this->db->query();
		}	
		
		//parse filter
		$filter = '';
		$search = JRequest::getVar('search', '');
		if($search){
			$filter .= '&search='.$search;
		}
		
		$this->setRedirect("index2.php?option=com_frontenduseraccess&view=usergroups".$filter, JText::_('USERGROUP_DELETED'));
	}
	
	function components_save(){
	
		// Check for request forgeries 
		JRequest::checkToken() or jexit('Invalid Token');
		
		$components_access_hidden = JRequest::getVar('components_access_hidden', null, 'post', 'array');		
		
		//get current component access
		$this->db->setQuery("SELECT component_groupid FROM #__fua_components");
		$access_components = $this->db->loadResultArray();
		
		//write section access	
		for($n = 0; $n < count($components_access_hidden); $n++){
			$value = $components_access_hidden[$n];
			$value_array = explode('__',$value);
			$right = $value_array[0].'__'.$value_array[1];			
			$selected = $value_array[3];
			
			//if right is now selected, but was not in table, do insert
			if($selected && !in_array($right,$access_components)){
				$this->db->setQuery( "INSERT INTO #__fua_components SET component_groupid='$right'");
				$this->db->query();
			}
			
			//if right is not selected, but was in table, take it out
			if(!$selected && in_array($right,$access_components)){				
				$this->db->setQuery("DELETE FROM #__fua_components WHERE component_groupid='$right'");
				$this->db->query();
			}
		}
		
		//parse filter
		$filter = '';
		$search = JRequest::getVar('search', '');
		if($search){
			$filter .= '&search='.$search;
		}
			
		$this->setRedirect("index2.php?option=com_frontenduseraccess&view=components".$filter, JText::_('COMPONENT_ACCESS_SAVED'));
	}	
	
	function empty_table($table_name){		
		
		if($table_name=='userindex' || $table_name=='menuaccess'){
			$this->db->setQuery("TRUNCATE TABLE #__fua_$table_name");
			if (!$this->db->query()){
				echo "<script> alert('".$this->db -> getErrorMsg()."'); window.history.go(-1); </script>";
				exit();
			}
		}else{
			exit();
		}
	}		
	
	function config_save(){
	
		// Check for request forgeries 
		JRequest::checkToken() or jexit('Invalid Token');
	
		$message_no_item_access_full = JRequest::getVar('message_no_item_access_full', '', 'post');
		$message_no_item_access_full = str_replace('"','&quot;',$message_no_item_access_full);
		$message_no_item_access = JRequest::getVar('message_no_item_access', '', 'post');
		$message_no_item_access = str_replace('"','&quot;',$message_no_item_access);
		$message_no_category_access = JRequest::getVar('message_no_category_access', '', 'post');
		$message_no_category_access = str_replace('"','&quot;',$message_no_category_access);
		$message_no_section_access = JRequest::getVar('message_no_section_access', '', 'post');
		$message_no_section_access = str_replace('"','&quot;',$message_no_section_access);		
		$message_no_component_access = JRequest::getVar('message_no_component_access', '', 'post');
		$message_no_component_access = str_replace('"','&quot;',$message_no_component_access);	
		$message_no_menu_access = JRequest::getVar('message_no_menu_access', '', 'post');
		$message_no_menu_access = str_replace('"','&quot;',$message_no_menu_access);		
		$redirect_url = JRequest::getVar('redirect_url', '', 'post');
		$redirect_url = str_replace('=','[equal]',$redirect_url);
		$no_item_access_full_url = JRequest::getVar('no_item_access_full_url', '', 'post');
		$no_item_access_full_url = str_replace('=','[equal]',$no_item_access_full_url);	
		$no_category_access_url = JRequest::getVar('no_category_access_url', '', 'post');
		$no_category_access_url = str_replace('=','[equal]',$no_category_access_url);
		$no_section_access_url = JRequest::getVar('no_section_access_url', '', 'post');
		$no_section_access_url = str_replace('=','[equal]',$no_section_access_url);
		$no_component_access_url = JRequest::getVar('no_component_access_url', '', 'post');
		$no_component_access_url = str_replace('=','[equal]',$no_component_access_url);
		$no_menu_access_url = JRequest::getVar('no_menu_access_url', '', 'post');
		$no_menu_access_url = str_replace('=','[equal]',$no_menu_access_url);
		
						
				$config = 'default_tab='.JRequest::getVar('default_tab', '', 'post').'
show_joomla_group_select='.JRequest::getVar('show_joomla_group_select', '', 'post').'
default_usergroup='.JRequest::getVar('default_usergroup', '', 'post').'
redirect_url='.$redirect_url.'
display_usergroups='.JRequest::getVar('display_usergroups', '0', 'post').'
display_users='.JRequest::getVar('display_users', '', 'post').'
display_items='.JRequest::getVar('display_items', '', 'post').'
items_active='.JRequest::getVar('items_active', '', 'post').'
items_reverse_access='.JRequest::getVar('items_reverse_access', '', 'post').'
items_message_type='.JRequest::getVar('items_message_type', 'alert', 'post').'
no_item_access_full_url='.$no_item_access_full_url.'
message_no_item_access_full='.addslashes($message_no_item_access_full).'
items_display_type='.JRequest::getVar('items_display_type', 'hide', 'post').'
message_no_item_access='.addslashes($message_no_item_access).'
truncate_article_title='.JRequest::getVar('truncate_article_title', '', 'post').'
display_categories='.JRequest::getVar('display_categories', '', 'post').'
categories_active='.JRequest::getVar('categories_active', '', 'post').'
category_reverse_access='.JRequest::getVar('category_reverse_access', '', 'post').'
category_message_type='.JRequest::getVar('category_message_type', 'alert', 'post').'
message_no_category_access='.addslashes($message_no_category_access).'
no_category_access_url='.$no_category_access_url.'
display_sections='.JRequest::getVar('display_sections', '', 'post').'
sections_active='.JRequest::getVar('sections_active', '', 'post').'
sections_reverse_access='.JRequest::getVar('sections_reverse_access', '', 'post').'
section_message_type='.JRequest::getVar('section_message_type', '', 'post').'
message_no_section_access='.addslashes($message_no_section_access).'
no_section_access_url='.$no_section_access_url.'
display_modules='.JRequest::getVar('display_modules', '', 'post').'
modules_active='.JRequest::getVar('modules_active', '', 'post').'
modules_reverse_access='.JRequest::getVar('modules_reverse_access', '', 'post').'
docman_workaround='.JRequest::getVar('docman_workaround', '', 'post').'
display_components='.JRequest::getVar('display_components', '', 'post').'
use_componentaccess='.JRequest::getVar('use_componentaccess', '', 'post').'
component_reverse_access='.JRequest::getVar('component_reverse_access', '', 'post').'
components_message_type='.JRequest::getVar('components_message_type', 'alert', 'post').'
message_no_component_access='.addslashes($message_no_component_access).'
no_component_access_url='.$no_component_access_url.'
use_menuaccess='.JRequest::getVar('use_menuaccess', '', 'post').'
menu_reverse_access='.JRequest::getVar('menu_reverse_access', '', 'post').'
display_menuaccess='.JRequest::getVar('display_menuaccess', '', 'post').'
menuaccess_message_type='.JRequest::getVar('menuaccess_message_type', 'text', 'post').'
message_no_menu_access='.addslashes($message_no_menu_access).'
no_menu_access_url='.$no_menu_access_url.'
display_joomla_access_levels='.JRequest::getVar('display_joomla_access_levels', '', 'post').'
';

		//update config
		$this->db->setQuery( "UPDATE #__fua_config SET config='$config' WHERE id='fua' ");
		$this->db->query();	
		
		//if module access is enabled, make sure classnames are correct
		if(JRequest::getVar('modules_active', '', 'post')){
			$this->module_classes();
		}else{
			//module access disabled, so take classnames out
			$this->module_classes_remove();
		}
		
		//redirect			
		if(JRequest::getVar('sub_task', '')=='apply'){
			$url = 'index2.php?option=com_frontenduseraccess&view=config';
		}else{
			$url = 'index2.php?option=com_frontenduseraccess';
		}	
		$this->setRedirect($url, JText::_('CONFIGSAVED'));
	}		

	function display_footer(){		
		echo '<div class="smallgrey" id="ua_footer"><a href="http://www.pages-and-items.com" target="_blank">Frontend-User-Access</a> &copy; '.strtolower(JText::_('version')).' '.$this->version.' (';		
		echo $this->fua_version_type.' version)';
		if($this->fua_version_type!='trial' && $this->fua_version_type!='trial'){
			echo ' <a href="http://www.gnu.org/licenses/gpl-2.0.html" target="blank">GNU/GPL License</a></div>';
		}
	}			

	function users_save(){
	
		// Check for request forgeries 
		JRequest::checkToken() or jexit('Invalid Token');
		
		$joomlagroups = JRequest::getVar('gid', null, 'post', 'array');	
		$user_ids = JRequest::getVar('user_id', null, 'post', 'array');	
		$usergroups = JRequest::getVar('usergroup', null, 'post', 'array');				
		
		//get users in userindex			
		$this->db->setQuery("SELECT user_id FROM #__fua_userindex ");
		$user_ids_index = $this->db->loadResultArray();		
		
		//update users				
		for($n = 0; $n < count($user_ids); $n++){
			$user_id = $user_ids[$n];
			if($this->fua_config['show_joomla_group_select']){												
				$gid_update = '';							
				$gid_update = 'gid=\''.$joomlagroups[$n].'\'';
				$joomla_group_id = $joomlagroups[$n];		
				switch ($joomlagroups[$n]) {
				case 18:
					$usertype = 'Registered';
					break;
				case 19:
					$usertype = 'Author';
					break;
				case 20:
					$usertype = 'Editor';
					break;
				case 21:
					$usertype = 'Publisher';
					break;
				case 23:
					$usertype = 'Manager';
					break;
				case 24:
					$usertype = 'Administrator';
					break;	
				}			
				$this->db->setQuery( "UPDATE #__users SET $gid_update , usertype='$usertype' WHERE id='$user_id'" );
				$this->db->query();
				
				$this->db->setQuery("SELECT id "
				."FROM #__core_acl_aro "
				."WHERE value='$user_id' "			
				);
				$aros = $this->db->loadResultArray();
				$aro_id = $aros[0];
				
				//update aro id in aro group map
				$this->db->setQuery( "UPDATE #__core_acl_groups_aro_map SET group_id='$joomla_group_id' WHERE aro_id='$aro_id'" );
				$this->db->query();	
			}
			
			//update or insert user index
			$usergroup = $usergroups[$n];
			if(in_array($user_id, $user_ids_index)){
				if($usergroup=='0'){
					$this->db->setQuery("DELETE FROM #__fua_userindex WHERE user_id='$user_id' ");
					$this->db->query();
				}else{						
					$this->db->setQuery( "UPDATE #__fua_userindex SET group_id='$usergroup' WHERE user_id='$user_id' " );
					$this->db->query();	
				}
			}else{
				if($usergroup!='0'){
					$this->db->setQuery( "INSERT INTO #__fua_userindex SET user_id='$user_id', group_id='$usergroup' ");
					$this->db->query();
				}
			}
									
		}	
		
		//parse filters
		$filter = '';
		$search = JRequest::getVar('search', '');
		if($search){
			$filters .= '&search='.$search;
		}
		$joomla_group_filter = JRequest::getVar('joomla_group_filter', '');
		if($joomla_group_filter){
			$filters .= '&joomla_group_filter='.$joomla_group_filter;
		}
		$usergroup_filter = JRequest::getVar('usergroup_filter', '');
		if($usergroup_filter){
			$filters .= '&usergroup_filter='.$usergroup_filter;
		}
					
		$this->setRedirect('index2.php?option=com_frontenduseraccess&view=users'.$filters, JText::_('USERSSAVED'));		
	}		
	
	//take this out for free version
	function access_sections_save(){		
	
		// Check for request forgeries 
		JRequest::checkToken() or jexit('Invalid Token');	
		
		$section_access_hidden = JRequest::getVar('section_access_hidden', null, 'post', 'array');			
		
		//get current section access
		$this->db->setQuery("SELECT section_groupid FROM #__fua_sections");
		$access_sections = $this->db->loadResultArray();
		
		//write section access	
		for($n = 0; $n < count($section_access_hidden); $n++){
			$value = $section_access_hidden[$n];
			$value_array = explode('__',$value);
			$right = $value_array[0].'__'.$value_array[1];			
			$selected = $value_array[3];
			
			//if right is now selected, but was not in table, do insert
			if($selected && !in_array($right,$access_sections)){
				$this->db->setQuery( "INSERT INTO #__fua_sections SET section_groupid='$right'");
				$this->db->query();
			}
			
			//if right is not selected, but was in table, take it out
			if(!$selected && in_array($right,$access_sections)){				
				$this->db->setQuery("DELETE FROM #__fua_sections WHERE section_groupid='$right'");
				$this->db->query();
			}
		}
		
		//parse filter
		$filter = '';
		$search = JRequest::getVar('search', '');
		if($search){
			$filter .= '&search='.$search;
		}	
						
		$this->setRedirect("index2.php?option=com_frontenduseraccess&view=sections".$filter, JText::_('SECTION_ACCESS_SAVED'));
	}
	
	function access_items_save(){	
	
		// Check for request forgeries 
		JRequest::checkToken() or jexit('Invalid Token');		
		
		$item_access_hidden = JRequest::getVar('item_access_hidden', null, 'post', 'array');		
				
		//get current item access
		$this->db->setQuery("SELECT itemid_groupid FROM #__fua_items");
		$access_items = $this->db->loadResultArray();	
		
		//write item access		
		for($n = 0; $n < count($item_access_hidden); $n++){
			$value = $item_access_hidden[$n];
			$value_array = explode('__',$value);
			$right = $value_array[0].'__'.$value_array[1];			
			$selected = $value_array[3];
			
			//if right is now selected, but was not in table, do insert
			if($selected && !in_array($right,$access_items)){
				$this->db->setQuery( "INSERT INTO #__fua_items SET itemid_groupid='$right'");
				$this->db->query();
			}
			
			//if right is not selected, but was in table, take it out
			if(!$selected && in_array($right,$access_items)){				
				$this->db->setQuery("DELETE FROM #__fua_items WHERE itemid_groupid='$right'");
				$this->db->query();
			}
		}		
		
		//parse filter
		$filter = '';
		$search = JRequest::getVar('search', '');
		if($search){
			$filter .= '&search='.$search;
		}			
					
		$this->setRedirect('index2.php?option=com_frontenduseraccess&view=items'.$filter, JText::_('ITEM_ACCESS_SAVED'));
	}
	
	//take this out for free version
	function access_categories_save(){		
	
		// Check for request forgeries 
		JRequest::checkToken() or jexit('Invalid Token');
		
		$category_access_hidden = JRequest::getVar('category_access_hidden', null, 'post', 'array');		
		
		//get current cagegory access
		$this->db->setQuery("SELECT category_groupid FROM #__fua_categories");
		$access_categories = $this->db->loadResultArray();	
		
		//write category access	
		for($n = 0; $n < count($category_access_hidden); $n++){
			$value = $category_access_hidden[$n];
			$value_array = explode('__',$value);
			$right = $value_array[0].'__'.$value_array[1];			
			$selected = $value_array[3];
			
			//if right is now selected, but was not in table, do insert
			if($selected && !in_array($right,$access_categories)){
				$this->db->setQuery( "INSERT INTO #__fua_categories SET category_groupid='$right'");
				$this->db->query();
			}
			
			//if right is not selected, but was in table, take it out
			if(!$selected && in_array($right,$access_categories)){				
				$this->db->setQuery("DELETE FROM #__fua_categories WHERE category_groupid='$right'");
				$this->db->query();
			}
		}
		
		//parse filter
		$filter = '';
		$search = JRequest::getVar('search', '');
		if($search){
			$filter .= '&search='.$search;
		}		
							
		$this->setRedirect("index2.php?option=com_frontenduseraccess&view=categories".$filter, JText::_('CATEGORY_ACCESS_SAVED'));
	}		
	
	function loop_usergroups($usergroups){
		foreach($usergroups as $usergroup){
			if($usergroup->id=='9'){
				$name = JText::_('LOGGEDIN');
				$description = JText::_('LOGGEDIN_DESCRIPTION');
			}elseif($usergroup->id=='10'){
				$name = JText::_('NOT_LOGGEDIN');
				$description = JText::_('NOT_LOGGEDIN_DESCRIPTION');
			}else{
				$name = stripslashes($usergroup->name);
				$description = stripslashes($usergroup->description);
			}			
			echo '<th style="text-align:center;"><span class="editlinktip" onmouseover="return overlib(\''.addslashes($description).'\', CAPTION, \''.addslashes($name).'\', BELOW, RIGHT, WIDTH, 400);" onmouseout="return nd();" >'.$name.'</span></th>';
		}
	}
		
	function check_demo_time_left(){			
		if($this->fua_version_type=='trial'){			
			echo '<p style="text-align: center;">';
			echo '<span class="editlinktip" onmouseover="return overlib(\''.JText::_('DEMO_DAYS_LEFT_TIP').'\', CAPTION, \'&nbsp;\', BELOW, RIGHT, WIDTH, 400);" onmouseout="return nd();" >'.JText::_('DEMO_DAYS_LEFT').'</span>';
			echo ': ';
			if(round((($this->fua_demo_seconds_left/60)/60)/24)<=0){
				echo '0';
			}else{
				echo round((($this->fua_demo_seconds_left/60)/60)/24);
			}
			echo '</p>';
		}
	}	
	
	function reverse_access_warning($which){
		echo '<p>';
		echo '<input type="checkbox" name="fua_legend_box" id="fua_legend_box" value="" checked="checked" onclick="this.checked=true" onfocus="if(this.blur)this.blur();" class="checkbox" /> = ';
		if($this->fua_config[$which]){				
			echo JText::_('USERGROUP_HAS_NO_ACCESS');
			echo '<img src="../includes/js/ThemeOffice/warning.png" class="warning_img" alt="be carefull" />'.JText::_('REVERSE_ACCESS_WARNING');
		}else{
			echo JText::_('USERGROUP_HAS_ACCESS');
		}
		echo '</p>';
	}
	
	function fua_check_trial_version(){
		//config		
		$fua_trial_valid_until = 1253610091;				
		$fua_allow_localhost = true;
		//check trial time left		
		$fua_trial_seconds_left = $fua_trial_valid_until-time();
		//let class know demo time left			
		$this->fua_demo_seconds_left = $fua_trial_seconds_left;		
		//check the trialtime
		$fua_trial_still_valid = false;	
		if(
		//check localhost
		($fua_allow_localhost && ($_SERVER['SERVER_NAME']==='localhost' || $_SERVER['SERVER_NAME']==='127.0.0.1')) ||
		//check demo time 
		$fua_trial_seconds_left >= 0 ||
		//not a trial version
		$this->fua_version_type == 'free' || $this->fua_version_type == 'pro'
		){					
			$fua_trial_still_valid = true;								
		}
		return $fua_trial_still_valid;
	}		

	//take this out for free version
	function modules_save(){	
	
		// Check for request forgeries 
		JRequest::checkToken() or jexit('Invalid Token');		
		
		$module_access_hidden = JRequest::getVar('module_access_hidden', null, 'post', 'array');
		
		//get current module access
		$this->db->setQuery("SELECT module_groupid FROM #__fua_modules_two");
		$access_modules = $this->db->loadResultArray();	
				
		//write module access	
		for($n = 0; $n < count($module_access_hidden); $n++){
			$value = $module_access_hidden[$n];
			$value_array = explode('__',$value);
			$right = $value_array[0].'__'.$value_array[1];			
			$selected = $value_array[3];
			
			//if right is now selected, but was not in table, do insert
			if($selected && !in_array($right,$access_modules)){
				$this->db->setQuery( "INSERT INTO #__fua_modules_two SET module_groupid='$right'");
				$this->db->query();				
			}
			
			//if right is not selected, but was in table, take it out
			if(!$selected && in_array($right,$access_modules)){				
				$this->db->setQuery("DELETE FROM #__fua_modules_two WHERE module_groupid='$right'");
				$this->db->query();			
			}
		}
		
		$this->module_classes();
		
		//parse filter
		$filter = '';
		$search = JRequest::getVar('search', '');
		if($search){
			$filter .= '&search='.$search;
		}		
					
		$this->setRedirect("index2.php?option=com_frontenduseraccess&view=modules".$filter, JText::_('MODULE_ACCESS_SAVED'));
	}
	
	function module_classes(){
		//get modules from database	
		$this->db->setQuery( "SELECT id, params "
		. "\nFROM #__modules "				
		. "\nWHERE client_id='0' "		
		);		
		$modules = $this->db->loadObjectList();
		
		foreach($modules as $module){
			$need_to_update = 0;			
			$id = $module->id;		
			$params = $module->params;			
						
			$classname = 'frontend_user_access_module_hide_'.$id.'_';			
			if(!strpos($params,'oduleclass_sfx=')){
				//suffix is not defined
				
				//insert suffix and class
				$params .= "\n".'moduleclass_sfx= '.$classname;				
				$need_to_update = 1;							
			}else{				
				//suffix is defined
				
				//get classes
				$current_classes = '';
				$pos = strpos($params,'oduleclass_sfx=');
				$temp = substr($params, $pos+15, 400);								
				if(strpos($temp,'=')){
					//not the last var						
					$pos2 = strpos($temp,"\n");
					$current_classes = substr($temp, 0, $pos2);					
				}else{						
					//last var						
					$current_classes = $temp;					
				}				
				$current_classes = $current_classes;							
				
					
				if($current_classes==''){	
					//there are no classes, so just insert the classname
					$params = str_replace('moduleclass_sfx=','moduleclass_sfx= '.$classname,$params);
					$need_to_update = 1;
				}else{	
					//there is one or more classname defined					
						
					$old_class_string = 'moduleclass_sfx='.$current_classes;			
					if(strpos($current_classes,'rontend_user_access_module_hide_')){
						//there is a fua class defines. need to check it (in case it is from a module that was copied)
																								
						$classes = explode(' ',$current_classes);
						$new_classes = '';
						$correct_class_name = 0;
						$wrong_class_name = 0;
						$has_new_classes = 0;
						foreach($classes as $class){
							if(strpos($class,'rontend_user_access_module_hide_')){
								//there is a fua class
								//leave the fua class out of the string in case of update							
								if($class==$classname){
									//the correct classname is in there
									$correct_class_name = 1;
								}else{
									//wrong classname
									$wrong_class_name = 1;
								}
							}else{
								//non fua classes									
								if($class!='' && $class!=' ' && $class!='  ' && $class!='   '){	
									//only add if its not just space						
									$new_classes .= $class.' ';										
								}							
							}
						}
						$new_class_string = 'moduleclass_sfx='.$new_classes;
						if($new_classes==''){
							$new_class_string .= ' ';
						}
						$new_class_string .= $classname;	
						//for performance we only update if needed
						if($wrong_class_name || !$correct_class_name){
							$need_to_update = 1;
						}					
					}else{
						//the class is not present, so we add it
						$new_class_string = 'moduleclass_sfx='.$current_classes.' '.$classname;
						$need_to_update = 1;
					}					
					$params = str_replace($old_class_string,$new_class_string,$params);										
				}										
			}			
					
			if($need_to_update){
				$this->db->setQuery( "UPDATE #__modules SET params='$params' WHERE id='$id' ");
				$this->db->query();	
			}			
		}		
	}	
	
	function module_classes_remove(){		
		$this->db->setQuery( "SELECT id, params "
		. "\nFROM #__modules "				
		. "\nWHERE client_id='0' "		
		);		
		$modules = $this->db->loadObjectList();
		
		foreach($modules as $module){			
			$id = $module->id;
			$params = $module->params;								
			$classname = 'frontend_user_access_module_hide_'.$id.'_';							
			if(strpos($params, $classname)){							
				$params = str_replace($classname,'',$params);
				$this->db->setQuery( "UPDATE #__modules SET params='$params' WHERE id='$id' ");
				$this->db->query();	
			}					
		}	
		echo 'frontend-user-access css classes where removed from all frontend modules';	
	}	
	
	function not_in_free_version(){
		if($this->fua_version_type=='free'){
			echo '<p class="warning">'.JText::_('NOT_IN_FREE_VERSION').'</p>';
		}
	}
	
	function menuaccess_save(){	
		
		// Check for request forgeries 
		JRequest::checkToken() or jexit('Invalid Token');
		
		$menu_access = JRequest::getVar('menu_access_hidden', null, 'post', 'array');			
		
		//get current menu access
		$this->db->setQuery("SELECT menuid_groupid FROM #__fua_menuaccess ");
		$menu_access_array = $this->db->loadResultArray();	
		
				
		//write menu access	
		for($n = 0; $n < count($menu_access); $n++){
			$value = $menu_access[$n];
			$value_array = explode('__',$value);
			$right = $value_array[0].'_'.$value_array[1];			
			$selected = $value_array[3];
			
			//if right is now selected, but was not in table, do insert
			if($selected && !in_array($right,$menu_access_array)){
				$this->db->setQuery( "INSERT INTO #__fua_menuaccess SET menuid_groupid='$right'");
				$this->db->query();				
			}
			
			//if right is not selected, but was in table, take it out
			if(!$selected && in_array($right,$menu_access_array)){				
				$this->db->setQuery("DELETE FROM #__fua_menuaccess WHERE menuid_groupid='$right'");
				$this->db->query();			
			}
		}		
						
		$this->setRedirect("index2.php?option=com_frontenduseraccess&view=menuaccess", JText::_('MENU_ACCESS_SAVED'));
	}	
	
	function pagination_get_limit(){
		global $mainframe;
		$limit = $mainframe->getUserStateFromRequest( 'global.list.limit', 'limit', $mainframe->getCfg('list_limit'), 'int' );
		//override limit 'all' with gets parsed as '0'!:-0. To get results from the query we need to override this
		if(!$limit){
			$limit = 99999999999999;
		}
		return $limit;
	}
	
	function pagination_get_limitstart(){
		global $mainframe, $option;
		$view = JRequest::getVar('view', '');		
		//get default limitstart
		$limitstart = $mainframe->getUserStateFromRequest( $option.'.limitstart', 'limitstart', 0, 'int' );
		//workaround for resetting limitstart when changing views
		$previous_view = $mainframe->getUserStateFromRequest( "$option.view", 'chocoladecake', '' );		
		$mainframe->setUserState( "$option.view",$view);
		//override limitstart when the filter has changed or when going to different view
		if($this->get_var('limitstart_needs_reset') || $previous_view!=$view){
			$limitstart = 0;
		}
		return $limitstart;
	}
	
	function pagination($total,$limitstart,$limit){
		jimport( 'joomla.html.pagination' );
		//reset override again, so limit 'all' is set to '0' again.
		if($limit==99999999999999){
			$limit = 0;
		}	  
		$pagination = new JPagination($total,$limitstart,$limit);
		return $pagination;
	}
	
	function usergroup_selector(){
		if (isset($_COOKIE["fua_selected_usergroups"])) {
			$fua_selected_usergroups = $_COOKIE["fua_selected_usergroups"];				
			$usergroup_array = array();
			$usergroup_array = explode(',',$fua_selected_usergroups);
			$cookie = 1;			
		}else{			
			$cookie = 0;				
		}			
		$this->db->setQuery("SELECT id, name, description "
		."FROM #__fua_usergroups "		
		."ORDER BY name "
		);		
		$usergroups = $this->db->loadObjectList();
		$html = JText::_('DISPLAY_USERGROUPS').': ';		
		$html .= '<select name="usergroup_selector[]" id="usergroup_selector" multiple="multiple" class="inputbox" size="7">';		
		$html .= '<option value="all" onclick="select_all_usergroups();">'.JText::_('all').'</option>';
		foreach($usergroups as $usergroup){
			$html .= '<option value="'.$usergroup->id.'"';
			if(!$cookie || ($cookie && in_array($usergroup->id,$usergroup_array))){
				$html .= ' selected="selected"';
			}
			$html .= '>';
			$html .= $usergroup->name;
			$html .= '</option>';
		}
		$html .= '</select>';
		$html .= '&nbsp;<button onclick="usergroups_to_cookie();this.form.submit();">'.JText::_('GO').'</button>';
		
		return $html;
	}
	
	
	function get_usergroups(){
		if (isset($_COOKIE["fua_selected_usergroups"])) {
			$fua_selected_usergroups = $_COOKIE["fua_selected_usergroups"];				
			$usergroup_array = array();
			$usergroup_array = explode(',',$fua_selected_usergroups);			
			$where = "WHERE id in ($fua_selected_usergroups) ";
		}else{
			$where = '';						
		}		
		$this->db->setQuery("SELECT id, name, description "
		."FROM #__fua_usergroups "
		.$where
		."ORDER BY name "
		);	
		$usergroups = $this->db->loadObjectList();
		return $usergroups;
	}	
	
	function ajax_update_users(){
		
		//check token
		JRequest::checkToken( 'get' ) or die( '<span style="color: red;">Invalid Token</span>' );
		
		//only super admins should do this
		if($this->user_type!='Super Administrator'){
			die('<span style="color: red;">only super administrators can move users to different groups</span>');
		}

		//get vars		
		$f = JRequest::getVar('f','','get','int');		
		$user_id = JRequest::getVar('u','','get','int');
		
		//check if user is in index table
		$this->db->setQuery("SELECT id, group_id FROM #__fua_userindex WHERE user_id='$user_id' ");			
		$index_data = $this->db->loadObjectList();
		$index_id = '';
		foreach($index_data as $data){				
			$index_id = $data->id;
			$group_id = $data->group_id;	
		}				
		
		if($index_id){
			if($f=='0'){
				//delete
				$this->db->setQuery("DELETE FROM #__fua_userindex WHERE id='$index_id'");
			}else{
				//update
				$this->db->setQuery( "UPDATE #__fua_userindex SET group_id='$f' WHERE user_id='$user_id' ");	
			}	
		}else{
			//insert
			$this->db->setQuery( "INSERT INTO #__fua_userindex SET group_id='$f', user_id='$user_id' ");		
		}
		$this->db->query();				
		
		//return update message
		echo '<span style="color: #5F9E30;">'.JText::_('UPDATED').'</span>';
		exit;
	}
	
	function batch_assign_ready(){
		$this->setRedirect("index2.php?option=com_frontenduseraccess&view=config&tab=users", JText::_('BATCH_ASSIGN_SUCCESS'));
	}
	
	function delete_old_module_table(){
		
		//check token
		JRequest::checkToken( 'get' ) or die( '<span style="color: red;">Invalid Token</span>' );
		
		//only super admins should do this
		if($this->user_type!='Super Administrator'){
			die('<span style="color: red;">only super administrators can delete the old module table</span>');
		}
		
		//check if table is really there
		$res = mysql_query("SELECT DATABASE()");
		$database_name = mysql_result($res, 0);
		
		$config =& JFactory::getConfig();
		$prefix = $config->getValue('dbprefix');
		
		$table_name = $prefix.'fua_modules';
		
		$res = mysql_query("
				SELECT COUNT(*) AS count 
				FROM information_schema.tables 
				WHERE table_schema = '$database_name' 
				AND table_name = '$table_name'
			");								
			
		if(mysql_result($res, 0) == 1){
			//do delete the old table
			$this->db->setQuery("DROP TABLE #__fua_modules");
			$this->db->query();				
		}
		
		$url = 'index2.php?option=com_frontenduseraccess&view=modules';
		$this->setRedirect($url, JText::_('OLD_MODULES_TABLE_DELETED'));			
	}
	
	function truncate_string($string, $length){
		$dots='...';
		$string = trim($string);		
		if(strlen($string)<=$length){
			return $string;	
		}
		if(!strstr($string," ")){
			return substr($string,0,$length).$dots;
		}	
		$lengthf = create_function('$string','return substr($string,0,strrpos($string," "));');	
		$string = substr($string,0,$length);	
		$string = $lengthf($string);
		while(strlen($string)>$length){
			$string=$lengthf($string);
		}	
		return $string.$dots;
	}
	
	

}
?>